package com.ftg.learn.chapter02.java.xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

/**
 * 解析xml -
 *
 * io : java.io
 * inputstream
 * outputstream
 * dom : org.w3c.dom
 * xml :
 * jdom
 * dom4j  : org.dom4j
 * saxreader
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/12/22 下午1:33
 */
public class ParseXml {

    public static void main(String[] args) {
        String path = "/home/kangjx/userpanel/workspace/java/learnjava2309/learnjava2309/src/main/resources/person.xml";

        //这是一个dom4j类，可以用来读取xml文件 ，底层是inputstream -->fileinputstream
        SAXReader kjx = new SAXReader();

        try {
            //读取xml文件
            Document document = kjx.read(new File(path));

            //获取根节点
            Element root = document.getRootElement();
            Attribute classPath = root.attribute("namespace");

            //获取子节点
            List<Element> elements = root.elements();

            //person
            elements.forEach(x->{
                Person p = new Person();

                Attribute id = x.attribute("id");
                p.setId(Integer.parseInt(id.getValue()));

                Attribute name = x.attribute("name");
                p.setName(name.getValue());
                System.out.println(p);
            });

            System.out.println("根节点:"+root.getName());

        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

}
